package org.example.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.erp.domain.FixtureTypes;
import org.example.erp.service.FixtureTypesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
public class FixtureTypeController {
    @Autowired
    FixtureTypesService fixtureTypesService;

    @GetMapping("/typeSettings/find")
    public DataResult find(
            @RequestParam(value = "typeCode") String typeCode,
            @RequestParam(value = "typeName") String typeName,
            @RequestParam(value = "maintenanceType") String maintenanceType,
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        boolean isAdmin = currentPage < 0;
        Page<FixtureTypes> page = new Page<>(currentPage, pageSize);
        QueryWrapper<FixtureTypes> queryWrapper = new QueryWrapper();
        if (typeCode != null && !typeCode.isEmpty()) {
            queryWrapper.lambda().like(FixtureTypes::getTypeCode, typeCode);
        }
        if (typeName != null && !typeName.isEmpty()) {
            queryWrapper.lambda().like(FixtureTypes::getTypeName, typeName);
        }
        if (maintenanceType != null && !maintenanceType.isEmpty()) {
            queryWrapper.lambda().like(FixtureTypes::getMaintenanceType, maintenanceType);
        }
        if (isAdmin) {
            return DataResult.success(fixtureTypesService.list());
        } else {
            page = fixtureTypesService.page(page, queryWrapper);
            return DataResult.success(page);
        }

    }

    @GetMapping("/typeSettings/findById")
    public DataResult findById(@RequestParam(value = "id") String id) {
        FixtureTypes fixtureTypes = fixtureTypesService.getById(id);
        return DataResult.success(fixtureTypes);
    }

    @PostMapping("/typeSettings/insert")
    public DataResult install(@RequestBody FixtureTypes fixtureTypes) {
        if (fixtureTypes.getMaintenanceType().isEmpty()) {
            fixtureTypes.setMaintenanceType(null);
        }
        boolean b = fixtureTypesService.save(fixtureTypes);
        return DataResult.success(b ? "成功" : "失败");
    }

    @PutMapping("/typeSettings/update")
    public DataResult update(@RequestBody FixtureTypes fixtureTypes) {
        boolean b = fixtureTypesService.updateById(fixtureTypes);
        return DataResult.success(b ? "成功" : "失败");
    }

    @DeleteMapping("/typeSettings/delete")
    public DataResult delete(@RequestBody List<String> id) {
        boolean b = fixtureTypesService.removeByIds(id);
        return DataResult.success(b ? "成功" : "失败");
    }

}
